package com.lemon.cloud.lock.aspect;

import com.lemon.cloud.lock.DistributedLock;
import com.lemon.cloud.lock.annotation.CacheLock;
import com.lemon.cloud.lock.generator.CacheKeyGenerator;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import java.lang.reflect.Method;

/**
 * @author lemon
 * @return
 * @description
 * @date 2019-09-05 12:58
 */
@Aspect
@Configuration
public class LockMethodInterceptor {
    @Autowired
    private DistributedLock distributedLock;

    @Autowired
    private CacheKeyGenerator cacheKeyGenerator;

    @Around("@annotation(cacheLock)")
    public Object interceptor(ProceedingJoinPoint proceedingJoinPoint, CacheLock cacheLock) throws Throwable {
        MethodSignature signature = (MethodSignature) proceedingJoinPoint.getSignature();
        Method method = signature.getMethod();
        CacheLock lock = method.getAnnotation(CacheLock.class);
        final String lockKey = cacheKeyGenerator.getLockKey(proceedingJoinPoint);

        try {
            this.distributedLock.lock(lockKey, lock.expire(), lock.timeUnit(), lock.retryTimes(), lock.sleepMillis());
            return proceedingJoinPoint.proceed();
        } finally {
            this.distributedLock.unlock(lockKey);
        }
    }
}